package com.company.dcm.server.tcp;

import com.company.dcm.server.protocol.ProtocolMessageDecoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

@Component
public class NettyServer {

    private int mainPort = 9989;
    private int OTAPort = 9990;
    private EventLoopGroup bossGroup = new NioEventLoopGroup(2);
    private EventLoopGroup workerGroup = new NioEventLoopGroup(16);
    private ChannelFuture channelFuture;

    public void start() throws Exception {
        startCon(mainPort,new  MainChannelInitializer());
        startCon(OTAPort,new OTAChannelInitializer());
    }



    public void startCon(int port,ChannelInitializer<SocketChannel> initializer) throws Exception {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(initializer)
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        // 绑定端口，开始接收进来的连接
        channelFuture = b.bind(port).sync();
        System.out.println("Netty Server started on port " + port);
    }



    @PreDestroy
    public void stop() throws Exception {
        System.out.println("Shutting down Netty server...");
        if (channelFuture!= null) {
            channelFuture.channel().close().sync();
        }
        workerGroup.shutdownGracefully().sync();
        bossGroup.shutdownGracefully().sync();
        System.out.println("Netty server has been shut down.");
    }
}
